package com.example.backtrack;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

public class SubSetSum {
    @Test
    public void test1() {
        System.out.println(123);
    }

    public void backTrack(List<Integer> state, List<List<Integer>> res, int[] choices, int target, int total) {
        if (total == target) {
            res.add(new ArrayList<>(state));
            return;
        }
        for (int i = 0; i < choices.length; i++) {
            if (total + choices[i] > target) {
                continue;
            }
            state.add(choices[i]);
            backTrack(state, res, choices, target, total + choices[i]);
            state.remove(state.size() - 1);
        }
    }

    // choices必须已经排序
    public void backTrackV2(List<Integer> state, List<List<Integer>> res, int[] choices, int target, int start) {
        if (target == 0) {
            res.add(new ArrayList<>(state));
            return;
        }
        for (int i = start; i < choices.length; i++) {
            if (target - choices[i] < 0) {
                break;
            }
            state.add(choices[i]);
            backTrackV2(state, res, choices, target - choices[i], i);
            state.remove(state.size() - 1);
        }

    }

    // choices必须已经排序
    public void backTrackV3(List<Integer> state, List<List<Integer>> res, int[] choices, int target, int start) {
        if (target == 0) {
            res.add(new ArrayList<>(state));
            return;
        }
        for (int i = start; i < choices.length; i++) {
            if (target - choices[i] < 0) {
                break;
            }
            if (i > start && choices[i] == choices[i - 1]) {
                continue;
            }
            state.add(choices[i]);
            backTrackV2(state, res, choices, target - choices[i], i);
            state.remove(state.size() - 1);
        }

    }
}
